package com.hxrd;

import com.jcraft.jsch.*;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.TimeUnit;

/**
 * @Description todo
 * @Author Administrator
 * @Date 2019/11/15 11:12
 **/
public class TestSqoop2 {
    private String ipAddress;
    private String username;
    private String password;
    public static final int DEFAULT_SSH_PORT = 22;
    private Vector<String> stdout;
    public TestSqoop2(final String ipAddress, final String username, final String password) {
        this.ipAddress = ipAddress;
        this.username = username;
        this.password = password;
        stdout = new Vector<String>();
    }
    public int execute(final String command) {
        int returnCode = 0;
        JSch jsch = new JSch();
        MyUserInfo userInfo = new MyUserInfo();
        try {
            // Create and connect session.
            Session session = jsch.getSession(username, ipAddress, DEFAULT_SSH_PORT);
            session.setPassword(password);
            session.setUserInfo(userInfo);
            session.connect();
            // Create and connect channel.
            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);
            channel.setInputStream(null);
            BufferedReader input = new BufferedReader(new InputStreamReader(channel
                    .getInputStream()));
            channel.connect();
            System.out.println("The remote command is: " + command);

            // Get the output of remote command.
            String line;
            while ((line = input.readLine()) != null) {
                stdout.add(line);
            }
            input.close();
            // Get the return code only after the channel is closed.
            if (channel.isClosed()) {
                returnCode = channel.getExitStatus();
            }
            // Disconnect the channel and session.
            channel.disconnect();
            session.disconnect();
        } catch (JSchException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnCode;
    }

    private String executeCommand(String host, String user, String password, List<String> cmds) {
        JSch jsch = new JSch();
        String result = "";
        StringBuilder sb = new StringBuilder();

        //	Channel channel = null;
        Session session = null;
        ChannelShell channelShell=null;
        try {
            session = jsch.getSession(user, host, 22);
            session.setPassword(password);
            session.setServerAliveCountMax(0);
            UserInfo ui = new MyUserInfo() {


                public String getPassword() {
                    System.out.println("MyUserInfo.getPassword()");
                    return "ruijie@wuhan01";
                }
                public boolean promptPassphrase(final String arg0) {
                    System.out.println("MyUserInfo.promptPassphrase()");
                    System.out.println(arg0);
                    return true;
                }
                public boolean promptPassword(final String arg0) {
                    System.out.println("MyUserInfo.promptPassword()");
                    System.out.println(arg0);
                    return true;
                }
                public void showMessage(String message) {
                    System.out.println(message);
                }

                public boolean promptYesNo(String message) {
                    return true;
                }
            };

            session.setUserInfo(ui);

            session.connect(30000); // making a connection with timeout.

            /*
             * channel = session.openChannel("shell"); String cmdsString = ""; for (String
             * cmd : cmds) { cmdsString += cmd+" \r\n"; } System.out.println(cmdsString);
             * InputStream is = new ByteArrayInputStream(cmdsString.getBytes());
             * channel.setInputStream(is); ByteArrayOutputStream baos = new
             * ByteArrayOutputStream(); channel.setOutputStream(baos);
             * System.out.println("channel1:" + channel.isConnected());
             * channel.connect(30000); TimeUnit.SECONDS.sleep(5); String tmpResult = new
             * String(baos.toByteArray()); // channel.connect(30000); // result+=tmpResult;
             * System.out.println(tmpResult);
             *
             */

            channelShell = (ChannelShell) session.openChannel("shell");
            channelShell.connect(3000);
            InputStream inputStream = channelShell.getInputStream();
            OutputStream outputStream = channelShell.getOutputStream();
            boolean stop = false;

            for (String cmd : cmds) {
                outputStream.write((cmd + "\n\r").getBytes());
                outputStream.flush();
                TimeUnit.MILLISECONDS.sleep(100);
                // BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
//                System.out.println(cmd);
                byte[] tmp = new byte[1024];
                while (true) {
                    while (inputStream.available() > 0) {
                        int i = inputStream.read(tmp, 0, 1024);
                        if (i < 0)
                            break;
                        String out = new String(tmp, 0, i);
                        if(cmd.contains("ap-config")||cmd.equalsIgnoreCase(" ")){
//                            if(out.indexOf("--More--")>0){
//                                out = out.substring(0, out.indexOf("--More--")-1);
//                            }
                            sb.append(out);
                        }
                        if(cmd.equalsIgnoreCase(" ")&&out.contains("WS6816#")){
                            stop = true;
                            break;
                        }
                        System.out.print(out);
                    }
                    if(stop){
                        result = sb.toString();
                        break;
                    }
                    TimeUnit.MILLISECONDS.sleep(100);
                    if (channelShell.isClosed()) {
                        if (inputStream.available() > 0)
                            continue;
                        stop = true;
                        System.out.println("exit-status: " + channelShell.getExitStatus());
                        break;
                    }
                    break;
                    // inputStream.close();
                }
                if(stop){
                    System.out.println("result is:"+result);
                    break;
                }
            }

        } catch (JSchException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (channelShell != null)
                channelShell.disconnect();
            if(session!=null)
                session.disconnect();
        }
        return result;
    }

    public Vector<String> getStandardOutput() {
        return stdout;
    }

    public static void main(final String [] args) {
//        TestSqoop2 sshExecutor = new TestSqoop2("223.75.63.163", "admin", "ruijie@wuhan01");
//        sshExecutor.execute("en");
//        Vector<String> stdout = sshExecutor.getStandardOutput();
//        for (String str : stdout) {
//            System.out.println(str);
//        }
        TestSqoop2 ts = new TestSqoop2("", "", "");
        List<String> cmds = new ArrayList<String>();

        cmds.add("en");
        cmds.add("ruijie@wuhan01");
        cmds.add("show ap-config sum | include Quit");
        for(int i=0;i<80;i++)
            cmds.add(" ");
        String ret = ts.executeCommand("223.75.63.163", "admin", "ruijie@wuhan01", cmds);
        if(!ret.equals("")){
            String devStr = ret.substring(ret.indexOf("-----\r\n")+6, ret.indexOf("Quit  \r\nWS6816#")+4);
            String newStr = devStr.replaceAll(" --More-- \b\b\b\b\b\b\b\b\b\b          \b\b\b\b\b\b\b\b\b\b", "");
            String[] devs = newStr.split("\r\n");
            for(String dev:devs){
                String val = dev.trim();
                String[] ele = val.split(" ");
                String macAddr = ele[0].replaceAll("\\.","");
                String[] dws = {"天", "时", "分", "秒"};
                String downTime = ele[ele.length-2]+":";
                for(String dw:dws){
                    downTime = downTime.replaceFirst(":", dw);
                }
                System.out.println("mac address is:"+macAddr + ", onlineTime is:"+downTime);
            }
            System.out.println("devs size is :"+devs.length);
        }
    }
}